<template>
  <div class="UploadFile-container">
    <el-upload
      v-if="!disabled"
      ref="upload"
      :action="`${define.comUploadUrl}/upload`"
      :headers="uploadHeaders"
      :file-list="fileList"
      :on-success="handleSuccess"
      :multiple="limit !== 1"
      :show-file-list="false"
      :accept="accept"
      :before-upload="beforeUpload"
      :on-exceed="handleExceed"
      :disabled="disabled"
      :limit="limit"
      :http-request="uploadFile"
      :auto-upload="false"
      :on-change="handleChange"
    >
      <el-button size="small" icon="el-icon-upload" :disabled="disabled">{{
        buttonText
      }}</el-button>
      <div slot="tip" class="el-upload__tip" v-show="showTip" v-if="!disabled">
        <span v-if="!tip">
          {{ `只能上传不超过${fileSize}${sizeUnit}的${handlerAccept}文件` }}
        </span>
        <span v-else>
          {{
            `${this.tip}且不超过${fileSize}${sizeUnit}的${handlerAccept}文件`
          }}
        </span>
      </div>
      <div slot="tip" class="el-upload__tip" v-show="!showTip">
        可上传Word、Excel、PPT、PDF等文档
      </div>
    </el-upload>
    <template v-if="fileList.length">
      <transition-group
        class="el-upload-list el-upload-list el-upload-list--text"
        tag="ul"
        name="el-list"
      >
        <li
          class="el-upload-list__item is-success"
          v-for="(file, index) in fileList"
          :key="index + 'ss'"
        >
          <a class="el-upload-list__item-name" @click="handleClick(file)">
            <i class="el-icon-document"></i>{{ file.name }}
          </a>
          <label class="el-upload-list__item-status-label">
            <i class="el-icon-upload-success el-icon-circle-check"></i>
          </label>
          <i
            class="el-icon-close"
            v-if="!disabled"
            @click="handleRemove(file, index)"
          ></i>
        </li>
      </transition-group>
    </template>
  </div>
</template>

<script>
import request from "@/utils/request";
const units = {
  KB: 1024,
  MB: 1024 * 1024,
  GB: 1024 * 1024 * 1024,
};
export default {
  name: "UploadFile",
  props: {
    value: {
      required: true,
      default: () => [],
    },
    type: {
      type: String,
      default: "",
    },
    // 是否只可以查看
    disabled: {
      type: Boolean,
      default: false,
    },
    showTip: {
      type: Boolean,
      default: false,
    },
    limit: {
      type: Number,
      default: 0,
    },
    accept: {
      type: String,
      default: "*",
    },
    buttonText: {
      type: String,
      default: "选择文件",
    },
    sizeUnit: {
      type: String,
      default: "MB",
    },
    fileSize: {
      default: 2,
    },
    tip: {
      type: String,
      default: "",
    },
  },
  data() {
    return {
      fileData: "",
      fileList: this.value,
      uploadHeaders: { Authorization: this.$store.getters.token },
      // baseUrl: process.env.VUE_APP_BASE_URL_FILE + "/file/upload",
      myTime: null,
    };
  },
  computed: {
    // 处理文件类型*展示问题
    handlerAccept() {
      if (this.accept.length === 1) {
        return "";
      }
      return this.accept.slice(0, this.accept.lastIndexOf("/"));
    },
  },
  watch: {
    value: {
      immediate: true,
      handler(val) {
        if (!val.length) {
          this.$emit("input", JSON.stringify(val));
        }
        if (typeof val === "string") {
          this.fileList = JSON.parse(val);
        } else {
          this.fileList = val;
        }
      },
    },
  },
  methods: {
    beforeUpload(file) {
      const unitNum = units[this.sizeUnit];
      if (!this.fileSize) return true;
      let isRightSize = file.size / unitNum < this.fileSize;
      if (!isRightSize) {
        this.$message.error(`文件大小超过${this.fileSize}${this.sizeUnit}`);
      }
      // let isAccept = new RegExp(this.accept).test(file.type)
      // if (!isAccept) {
      //   this.$message.error(`应该选择${this.accept}类型的文件`)
      // }
      return isRightSize;
    },
    //监控上传文件列表
    handleChange(file, fileList) {
      let existFile = fileList
        .slice(0, fileList.length - 1)
        .find((f) => f.name === file.name);
      if (existFile) {
        this.$message.error("当前文件已经存在!");
        fileList.pop();
      }
      this.fileList = fileList;
      clearTimeout(this.myTime);
      this.myTime = setTimeout(() => {
        this.submit();
      }, 100);
    },
    // 上传文件
    uploadFile(file) {
      this.fileData.append("file", file.file); // append增加数据
    },
    submit() {
      if (!this.fileList.length) {
        this.$message({
          message: "请先选择文件",
          type: "warning",
        });
      } else {
        const unitNum = units[this.sizeUnit];
        let currentUpload = this.fileList.filter((item) => item.size);
        const isLt100M = currentUpload.every(
          (file) => file.size / unitNum < this.fileSize
        );
        if (!isLt100M) {
          this.$message.error(
            `请检查，上传文件大小不能超过${this.fileSize}MB!`
          );
          this.fileList.forEach((item, index) => {
            if (item.size / 1024 / 1024 > this.fileSize) {
              this.fileList.splice(index, 1);
            }
          });
        } else {
          this.fileData = "";
          this.fileData = new FormData(); // new formData对象
          this.$refs.upload.submit(); // 提交调用uploadFile函数

          request({
            url: this.define.comUploadUrl + "/upload",
            method: "post",
            data: this.fileData,
            headers: { Authorization: this.$store.getters.token },
          }).then((res) => {
            this.fileList.forEach((item, index) => {
              res.data.forEach((item1) => {
                if (item.name == item1.name) {
                  this.$set(this.fileList, index, {
                    name: item1.name,
                    fileId: item1.fileId,
                    url: item1.ossAddress,
                  });
                }
              });
            });
            this.$emit("input", JSON.stringify(this.fileList));
          });
        }
      }
    },
    handleSuccess(res, file, fileList) {
      console.log("上传成功的钩子");
      if (!res.code) {
        this.fileList.push({
          name: file.name,
          fileId: res.data.fileId,
          ossAddress: res.data.ossAddress,
        });
        this.$emit("input", JSON.stringify(this.fileList));
      }
      // else {
      //   fileList.filter((o) => o.uid != file.uid);
      //   this.$emit("input", this.fileList);
      //   this.$message({ message: res.msg, type: "error", duration: 1500 });
      // }
    },
    handleExceed(files, fileList) {
      this.$message.warning(`当前限制最多可以上传${this.limit}个文件`);
    },
    handleRemove(file, index) {
      this.fileList.splice(index, 1);
      this.$emit("input", JSON.stringify(this.fileList));
      // this.$confirm(`确定移除${file.name}？`, '提示').then(() => {
      // }).catch(() => { })
    },
    handleClick(file) {
      // 点击下载文件
      if (!file.fileId) return;
      window.location.href = file.url;
    },
  },
};
</script>